<template>
    <div class="wrapper">
        <div class="hMain">
            <div class="hHead">
                <img v-lazy="headImg" alt="">
            </div>
            <wheel-word :lineHeight="lineHeight" :len="listLength" :id="id" ref="wheel" @selectRecord="selectRecord">
                <div class="wheel-word" v-show="show">
                    <div class="list-layer" id="wheel-word">
                        <div v-for="(item,index) in texts" :key="index">{{item.text}}</div>
                    </div>
                </div>
            </wheel-word>
            <div class="hVoice" @touchstart.stop.prevent="tStart()" @touchend.stop.prevent="tEnd()">
                <img src="http://rs.static.quanc.com.cn/activies/mfAct/voiceBtn.png" alt="">
            </div>
            <div class="voiceText">
                长按录音按键<br>读取祝福语
            </div>
        </div>
        <div class="voice-pop-layer" v-show="showVoice">
            <img src="http://rs.static.quanc.com.cn/activies/mfAct/voice.png">
        </div>
        <div class="return" @click="ret">
            <img src="http://rs.static.quanc.com.cn/activies/mfAct/left.png" alt="">
        </div>
        <!--<component-->
        <!--v-bind:is="showShareModule"-->
        <!--class="tab"-->
        <!--&gt;</component>-->
        <share :isshare="isshare"></share>
    </div>
</template>
<script>
    import {MessageBox} from "mint-ui";
    import {mapState, mapMutations} from "vuex";
    import * as config from "./config";
    import request from "@/utils/request";
    import wx from "weixin-js-sdk";
    //import wxsdk from "@/utils/wxsdk";
    import utils from "@/utils/utils";
    import Cookies from "js-cookie";
    import WheelWord from "@/components/common/WheelWord";
    import Share from "@/components/common/Share";

    export default {
        data() {
            return {
                lineHeight: 2, //rem
                listLength: 2, //循环长度
                id: "wheel-word",
                show: false,
                isshare: this.$route.query.isShare ? this.$route.query.isShare : false,
                showVoice: false,
                reOpenid: this.$route.query.reOpenid ? this.$route.query.reOpenid : '',
                openid: Cookies.get("openid"),

                headImg: 'http://rs.static.quanc.com.cn/activies/ztAct/zt_head.png',
                code: 'prize_4',
                isAward: false,
                stime: "",
                etime: "",
                matchedText: "",
                voice: {
                    localId: "",
                    serverId: ""
                },
                texts: [
                    {
                        text: "赠一束郁金香，结一生彰泰情",
                        id: 1
                    },
                    {
                        text: "开年迎好运，扬帆启新彰",
                        id: 2
                    },
                    {
                        text: "彰泰传佳音，片语表浓情",
                        id: 3
                    }
                ]
            };
        },

        computed: {
//        showShareModule: function () {
//            return 'share';
//        },
            ...mapState(["info", "channel"])
        },
        created() {
            if (!window.ConfigAudio) {
                window.ConfigAudio = new Audio()
                window.ConfigAudio.src = 'http://rs.static.quanc.com.cn/activies/mfAct/voice.mp3';
                wx.ready(function () {
                    window.ConfigAudio.play();
                });
            } else {
                window.ConfigAudio.src = 'http://rs.static.quanc.com.cn/activies/mfAct/voice.mp3';
                wx.ready(function () {
                    window.ConfigAudio.play();
                });
            }

            this.setChannel(this.$route.query.channel ? this.$route.query.channel : 0);
            if (!this.info.mobile) {
                request
                    .get(this.global.API_URL, {
                        action: "/activity/relay/RelayAction/getActUserInfo",
                        requestParam: {
                            actcode: config.ACT_CODE,
                            referenceopenid: ""
                        }
                    })
                    .then(response => {
                        this.setInfo(response.obj);
                        this.checkAward();
                        if (this.info && this.info.nickname && this.info.nickname != '') {
                            this.global.SHARE_TITLE = "大力士【" + this.info.nickname + "】摇中大礼，测测你的臂力"
                        }
                        this.global.SHARE_LINK = location.protocol + '//' + location.host + '/act/ztact/index?channel=' + this.channel + '&reOpenid=' + this.openid;
                    });
            } else {
                this.checkAward();
                this.global.SHARE_LINK = location.protocol + '//' + location.host + '/act/ztact/index?channel=' + this.channel + '&reOpenid=' + this.openid;
            }
        },
        components: {
            "wheel-word": WheelWord,
            share: Share
        },
        methods: {

            ret() {
                this.$router.push({path: '/index', query: {channel: this.channel, reOpenid:this.reOpenid}});
            },
            tStart(e) {
                //                this.$router.push("");

                let _self = this;
                _self.showVoice = true;
                _self.stime = Date.parse(new Date());
                //开始录音
                wx.startRecord({
                    cancel: function () {
                        _self.showVoice = false;
                        MessageBox.alert("用户拒绝授权录音", "提示");
                    }
                });
                //监听录音自动停止
                wx.onVoiceRecordEnd({
                    complete: function (res) {
                        _self.voice.localId = res.localId;
                        //                        translateVoice()
                    }
                });
                //                e.preventDefault();
                return false;
            },
            tEnd() {
                let _self = this;
                wx.stopRecord({
                    success: function (res) {
                        _self.voice.localId = res.localId;
                        //                        console.log(_self.voice.localId);
                        _self.showVoice = false;
                        _self.translateVoice();
                    },
                    fail: function (res) {
                        MessageBox.alert(res, "提示")
                    }
                });
            },
            translateVoice() {
                let _self = this;
                _self.etime = Date.parse(new Date());
                let time = (_self.etime - _self.stime) / 1000;
                if (time <= 0) {
                    time = 1;
                }
                wx.translateVoice({
                    localId: _self.voice.localId,
                    complete: function (res) {
                        if (res.hasOwnProperty("translateResult")) {
                            res.translateResult = res.translateResult.split("。")[0];
                            if (utils.textMatch(_self.matchedText, res.translateResult, 0.5)) {
                                wx.uploadVoice({
                                    localId: _self.voice.localId,
                                    success: function (res) {
                                        _self.voice.serverId = res.serverId;
                                        if (_self.isAward) {
                                            MessageBox.alert("您已经领过奖了！", "提示")
                                        } else {
                                            MessageBox.alert("小发收到了您的祝福，一份价值3000元的购房优惠券送上。", "恭喜").then(function () {
                                                _self.submitVoice(time);
                                            })

                                        }

                                    }
                                });
                            } else {
                                MessageBox.alert(
                                    "要字正腔圆哦，再试一次！购房券已迫不及待，等你带走！",
                                    "提示"
                                ).then(() => {
                                    window.ConfigAudio.play();
                                    _self.show = false;
                                    _self.$nextTick(() => {
                                        _self.show = true;
                                    });
                                });
                            }
                        } else {
                            MessageBox.alert("无法识别", "提示").then(() => {
                                window.ConfigAudio.play();
                                _self.show = false;
                                _self.$nextTick(() => {
                                    _self.show = true;
                                });
                            });
                        }
                    }
                });
            },
            submitVoice(time) {
                let _self = this;
                const obj = {
                    projectid: 20190119,
                    voiceid_matched: _self.voice.serverId,
                    voice_matched_secs: time,
                    voice_text: _self.matchedText
                };
                request
                    .get(this.global.API_URL, {
                        action: "/activity/stt/SttAction/saveVoice",
                        requestParam: {
                            obj: obj
                        }
                    })
                    .then(response => {
                        let mark = response.mark;

                        if (mark == '1') {
                            //中购房优惠券
                            //            MessageBox.alert("中购房优惠券！", "提示").then(()=>{
                            //判断是否提交过用户信息
                            if (_self.info && _self.info.mobile) {
                                _self.$router.push({
                                    path: "/info",
                                    query: {
                                        code: _self.code,
                                        channel: _self.channel,
                                        reOpenid: _self.reOpenid,
                                        mobile: _self.info.mobile,
                                        name: _self.info.name
                                    }
                                });
//                request
//                    .get(this.global.API_URL, {
//                        action: "/activity/relay/RelayAction/getZHPrize",
//                        requestParam: {
//                            actcode: config.ACT_CODE,
//                            prizecode: _self.code
//                        }
//                    })
//                    .then(response => {
//                        if (response.obj == 1) {
//                            MessageBox.alert("恭喜您获得3000元购房优惠券！", "提示").then(
//                                () => {
//                                    _self.isShare = true;
//                                }
//                            );
//                        }else{
//                            MessageBox.alert(JSON.stringify(response), "提示")
//                        }
//                    });

                            } else {
                                _self.$router.push({path: "/info", query: {code: _self.code, channel: _self.channel, reOpenid: _self.reOpenid}});
                            }
                            //            });
                        } else if (mark == 0) {
                            //没有匹配成功
                            MessageBox.alert("没有匹配成功！", "提示");
                        }
                    });
            },
            selectRecord(index) {
                //选中的记录
                this.matchedText = this.texts[index].text;
            },
            checkAward() {
                //获取是否领过奖
                request
                    .get(this.global.API_URL, {
                        action: "/activity/relay/RelayAction/getUserPrize",
                        requestParam: {
                            actcode: config.ACT_CODE
                        }
                    })
                    .then(response => {
                        this.isAward = config.checkaward(response.obj, this.code);
                    });
            },
            ...mapMutations({
                setInfo: "SET_INFO",
                setChannel: "SET_CHANNEL"
            })
        },
        mounted() {
            this.show = true;
            let _self = this;
            this.global.SHARE_CALLBACK_OK = function (type) {
                request
                    .get(_self.this.global.API_URL, {
                        action: "/activity/relay/RelayAction/share",
                        requestParam: {
                            actcode: config.ACT_CODE,
                            groupcode: config.ACT_CODE,
                            prizecode: 'prize_1',
                            channel: _self.channel,
                            referenceopenid: _self.reOpenid
                        }
                    })
                    .then(response => {

                    });
            };
            config.initShare();


//      _self.channel=_self.$route.query.channel ? _self.$route.query.channel : 0;
            _self.reOpenid = _self.$route.query.reOpenid ? _self.$route.query.reOpenid : '';


            //            request
            //                .get(this.global.API_URL, {
            //                    action: "/activity/stt/SttAction/submitVoice",
            //                    requestParam:{
            //                        obj:{
            //                            projectid: 20190119,
            //                            from_openid: Cookies.get("openid"),
            //                            voiceid_matched: 313131,
            //                            voice_matched_secs:231313131,
            //                            voice_text:'明发集团礼献万众'
            //                        }
            //                    }
            //                })
            //                .then(response => {
            //                    MessageBox.alert(JSON.stringify(response), "提示");
            //                    let mark = response.mark;
            //                    if (mark == 1) {//中购房优惠券
            //                        MessageBox.alert("中购房优惠券！", "提示");
            //                    } else if (mark == 0) {//没有匹配成功
            //                        MessageBox.alert("没有匹配成功！", "提示");
            //                    }
            //                });
        }
    };
</script>
<style lang="stylus" scoped>
    @import '~@/assets/styles/mixins.styl';
    * {
        -webkit-touch-callout: none;
        -webkit-user-select: none;
        -khtml-user-select: none;
        -moz-user-select: none;
        -ms-user-select: none;
        user-select: none;
    }

    img {
        pointer-events: none;
    }

    .wrapper {
        position absolute
        top: 0
        left: 0
        bottom: 0
        right: 0
        background: url('http://rs.static.quanc.com.cn/activies/ztAct/voice_bg.jpg') repeat center center;
        background-size: 100% 100%;
    }

    .hMain {
        position absolute
        top: 15%
        width 100%
    }
    .hHead{
        width 100%
        text-align center
        padding .3rem 0
    }
    .hHead>img{
        width 1.5rem
        height 1.5rem
        border-radius 50%
        border .1rem solid #fec500
    }
    .hVoice {
        width: 20%
        margin 0 auto
        margin-top: .2rem
    }

    .hVoice > img {
        width: 100%
        height: 100%
    }

    .hTextImg {
        padding-top .3rem
        width: 40%
        margin 0 auto
    }

    .hTextImg > img {
        width: 100%
        height: 100%
    }
    .voiceText{
        width: 100%
        text-align center
        padding-top .2rem
        font-size .32rem
        line-height .6rem
        color #fff
    }

    .voice-pop-layer {
        position: absolute;
        display: -webkit-box;
        -webkit-box-orient: horizontal;
        -webkit-box-pack: center;
        -webkit-box-align: center;
        /*width: 100%;*/
        -webkit-user-select: none;
        top: 3rem;
        left: 50%;
        margin-left: -12.5%;
        height: 2rem;
        width: 25%;
        border-radius: 15px;
        background: rgba(0, 0, 0, .5);
    }

    .return {
        position absolute
        top: 1rem
        left 0
        width: 2rem
    }

    .return > img {
        width: 100%
        height: 100%
    }

    .wheel-word
        width: 6rem
        background: #fff
        margin 0 auto
        height: 2rem
        border-radius: .5rem
        font-size: .36rem
        color: #cb0709
        overflow: hidden
        display flex
        flex-direction: column
        align-items center
    // justify-content center
        .list-layer
            > div
                min-height 2rem
                line-height: 1rem
                text-align: center
                display flex
                align-items center
                justify-content center
                padding 0 .5rem
</style>
